package cn.exrick.xboot.common.utils;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Slf4j
public class UploadAndDownloadUtils {
  //上传到服务器文件夹中
  public final static String UPLOAD_PATH_PREFIX = "static/uploadFile/";
  public static String uploadUtils(MultipartFile uploadFile, HttpServletRequest request){
    if(uploadFile.isEmpty()){
      //返回选择文件提示
      return "请选择上传文件";
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    //构建文件上传所要保存的"文件夹路径"--这里是相对路径，保存到项目根路径的文件夹下
    String realPath = new String("xboot-fast/src/main/resources/" + UPLOAD_PATH_PREFIX);
    log.info("-----------上传文件保存的路径【"+ realPath +"】-----------");
    String format = sdf.format(new Date());
    //存放上传文件的文件夹
    File file = new File(realPath + format);
    log.info("-----------存放上传文件的文件夹【"+ file +"】-----------");
    log.info("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径【"+ file.getAbsolutePath() +"】-----------");
    if(!file.isDirectory()){
      //递归生成文件夹
      file.mkdirs();
    }
    //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
    String oldName = uploadFile.getOriginalFilename();
    log.info("-----------文件原始的名字【"+ oldName +"】-----------");
    String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());
    log.info("-----------文件要保存后的新名字【"+ newName +"】-----------");
    try {
      //构建真实的文件路径
      File newFile = new File(file.getAbsolutePath() + File.separator + oldName);
      //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
      uploadFile.transferTo(newFile);
      String filePath =  "/uploadFile/" + format + oldName;
      return filePath;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "上传失败!";
  }
//视频资源
public static void downLoadVido(HttpServletResponse response,String filePath){
  String[] uploadFiles = filePath.split("uploadFile");
  String property = System.getProperty("user.dir");
  filePath =property+"\\xboot-fast\\src\\main\\resources\\static\\uploadFile"+uploadFiles[1];
  try{
    FileInputStream ff=new FileInputStream(filePath);
    OutputStream out=null;
    int size=ff.available();
    byte[] data=new byte[size];
    ff.read(data);
    ff.close();
    ff=null;
    response.setContentType("video/mp4");
    out=response.getOutputStream();
    out.write(data);
    out.flush();
    out.close();
  }catch(Exception e){
    e.printStackTrace();
  }
}

  //下载
  public static void downLoad(HttpServletResponse response,String filePath)throws UnsupportedEncodingException{
    String[] uploadFiles = filePath.split("uploadFile");
    String property = System.getProperty("user.dir");
    filePath =property+"\\xboot-fast\\src\\main\\resources\\static\\uploadFile"+uploadFiles[1];

    File file = new File(filePath);
    String filename = file.getName();
    if(file.exists()){ //判断文件父目录是否存在
      response.setContentType("application/vnd.ms-excel;charset=UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "iso8859-1"));
      byte[] buffer = new byte[1024];
      FileInputStream fis = null; //文件输入流
      BufferedInputStream bis = null;

      OutputStream os = null; //输出流
      try {
        os = response.getOutputStream();
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        int i = bis.read(buffer);
        while(i != -1){
          os.write(buffer);
          i = bis.read(buffer);
        }

      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      System.out.println("----------file download---" + filename);
      try {
        bis.close();
        fis.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
 //文件转字符串
  public  static  String  handleStrToFile(String str){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    String realPath = new String("xboot-fast/src/main/resources/" + UPLOAD_PATH_PREFIX);
    String format = sdf.format(new Date());
    File file = new File(realPath + format);
    if(!file.isDirectory()){
      //递归生成文件夹
      file.mkdirs();
    }
    String newName = UUID.randomUUID().toString() + ".text";
    File newFile = new File(file.getAbsolutePath() + File.separator + newName);
    String backFileName=realPath + format+newName;
    FileWriter fwriter = null;
    try {
      // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
      fwriter = new FileWriter(newFile.getPath(), true);
      fwriter.write(str);
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
        fwriter.flush();
        fwriter.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return backFileName;
  }
  //文件转字符串
  //文件转字符串
  public  static  String  handleFileToStr(String filePath) throws Exception{
    String property = System.getProperty("user.dir");
    filePath =property+"\\"+ filePath;
    StringBuffer buffer = new StringBuffer();
    BufferedReader bf= new BufferedReader(new FileReader(filePath));
    String s = null;
    while((s = bf.readLine())!=null){//使用readLine方法，一次读一行
      buffer.append(s.trim());
    }
    String str = buffer.toString();
    return str;
  }
  //删除文件
  public static void deleteFile(String filePath){
    String[] uploadFiles = filePath.split("uploadFile");
    String property = System.getProperty("user.dir");
    filePath =property+"\\xboot-fast\\src\\main\\resources\\static\\uploadFile"+uploadFiles[1];
    File file = new File(filePath);// 读取
    file.delete();
  }
  ///////////
  /*public static void fetchFrame(String videofile, HttpServletResponse response)
          throws Exception {
    String property = System.getProperty("user.dir");
    videofile =property+"\\"+ videofile;
    File file=new File(videofile);
    String name = file.getName();
    long start = System.currentTimeMillis();
    FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);

    ff.start();
    int lenght = ff.getLengthInFrames();
    int i = 0;
    Frame f = null;
    org.bytedeco.javacv.Frame frame = ff.grabFrame();
    while (i < lenght) {
      // 过滤前5帧，避免出现全黑的图片，依自己情况而定
      frame = ff.grabFrame();

      if ((i > 5) && (frame.image != null)) {
        break;
      }
      i++;
    }
    opencv_core.IplImage img = frame.image;
    int owidth = img.width();
    int oheight = img.height();
    // 对截取的帧进行等比例缩放
    int width = 800;
    int height = (int) (((double) width / owidth) * oheight);
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    bi.getGraphics().drawImage(frame.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
            0, 0, null);
    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + new String("name".getBytes("UTF-8"), "iso8859-1"));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(bi, "jpg", out);
    byte[] bytes = out.toByteArray();
    ServletOutputStream outputStream = response.getOutputStream();
    outputStream.write(bytes);
    outputStream.flush();
    outputStream.close();
  }*/
  /*public static InputStream uploadPicture(MultipartFile uploadFile) {
    //1、给上传的图片生成新的文件名
    //1.1获取原始文件名
    String oldName = uploadFile.getOriginalFilename();
    //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
    String newName = IDUtils.genImageName();
    assert oldName != null;
    newName = newName + oldName.substring(oldName.lastIndexOf("."));
    //1.3生成文件在服务器端存储的子目录
    String filePath = new DateTime().toString("/yyyyMMdd/");
    //2、把图片上传到图片服务器
    //2.1获取上传的io流
    InputStream input = null;
    try {
      input = uploadFile.getInputStream();
    } catch (IOException e) {
      e.printStackTrace();
    }
    //2.2调用FtpUtil工具类进行上传

    FtpUtil.putImages(input, filePath, newName);
    return input;
  }*/
}
